/*
 * @Author: your name
 * @Date: 2022-04-10 17:41:26
 * @LastEditTime: 2022-04-13 20:17:12
 * @LastEditors: Please set LastEditors
 * @Description: 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 * @FilePath: \drivingTow\src\score\score.service.ts
 */
import { Injectable } from '@nestjs/common';
import { InjectRepository } from '@nestjs/typeorm';
import { Repository } from 'typeorm';
import { CreateScoreDto, ScoreInfoDto, ScoreRo } from './dto/create-score.dto';
import { UpdateScoreDto } from './dto/update-score.dto';
import { Score } from './entities/score.entity';

@Injectable()
export class ScoreService {
  constructor(
    @InjectRepository(Score)
    private readonly postsRepository:Repository<Score>
  ){}
  // 创建评分表
  async createScore(post: CreateScoreDto):Promise<any> {
    const newPost:Score = await this.postsRepository.create({
      ...post,
    })
    const created = await this.postsRepository.save(newPost)
    return created
  }

  // 评分
  async makeScore(post):Promise<any>{
    const qb = this.postsRepository
      .createQueryBuilder('Score')
      .where('Score.trainee =:trainee',{trainee:post.trainee})
      .andWhere('Score.create_time =:create_time',{create_time:post.create_time})
      .getOne()
    if((await qb).status === "NotRated"){
      const qbTwo = this.postsRepository
      .createQueryBuilder('Score')
      .update()
      .set({status:'Evaluated',content:post.content,score:post.score})
      .where('Score.trainee =:trainee',{trainee:post.trainee})
      .andWhere('Score.create_time =:create_time',{create_time:post.create_time})
      .execute()
      return 'success'
    }
    else{
      return '学员已评价'
    }
  }

  // 管理员查看所有评分记录
  async getAllScore(obj):Promise<ScoreRo>{
    const qb = this.postsRepository
      .createQueryBuilder('Score')
      .where('1=1')
    const Total = await qb.getCount();
    const {pageSize,pageNum} = obj
    qb.limit(pageSize)
    qb.offset(pageSize * (pageNum - 1))
    let Score = await qb.getMany();
    const result:ScoreInfoDto[] = Score.map((item) => item.toResponseObject());
    return {list:result,Total:Total}
  }

  // 计算平均评分
  async getAverageScore(post){
    const qb =this.postsRepository
      .createQueryBuilder('Score')
      .where('Score.coach=:coach and Score.catogary=:catogary',{coach:post.coach,catogary:post.catogary})
    const result =await qb.getMany()
    const total =await qb.getCount()
    let sum = 0
    ;(await result).forEach(item =>{
      sum = sum + item.score
    })
    let avg = sum / total
    return {avg:avg}
  }

  // 管理员删除评价
  async deleteScore(id){
    const Score = await this.postsRepository.findOne(id)
    return await this.postsRepository.remove(Score)
  }
}
